package com.rover.system.controller;

import com.grid.DataGrid;
import com.grid.Page;

import com.rover.system.entity.Department;
import com.rover.system.service.DepartmentService;
import com.utils.JsonUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公开访问
 */
@Controller
@RequestMapping("/departmentController")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    @RequestMapping("/query")
    @ResponseBody
    public Map<String, Object> query(HttpServletRequest request, Page page, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String name = request.getParameter("name");
        Map<String, Object> params = new HashMap<String, Object>();
        String hql = " where 1=1";
        if (StringUtils.isNotBlank(name)) {
            hql += " and deptName like:deptName";
            params.put("deptName", "%" + name + "%");
        }
        String deptCode = request.getParameter("deptCode");
        if (StringUtils.isNotBlank(deptCode)) {
            hql += " and deptCode like:deptCode and deptCode<>:deptCode2";
            params.put("deptCode", deptCode + "%");
            params.put("deptCode2", deptCode);
        }
        else{
            hql += " and deptCode like:deptCode ";
            params.put("deptCode", "___");

        }


        DataGrid dataGrid = departmentService.query(page, params, hql);
        map = JsonUtil.JSONString(dataGrid.getResult(),
                dataGrid.getTotalCount());
        return map;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public
    @ResponseBody
    Map<String, Object> save(Department department, HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Boolean success = true;
        try {
            departmentService.save(department);
            map.put("success", success);
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public
    @ResponseBody
    Map<String, Object> update(Department department, HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        Boolean success = true;
        try {
            departmentService.update(department);
            map.put("success", success);
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public
    @ResponseBody
    Map<String, Object> delete(@RequestParam("id") List<Integer> deptCodes) {
        Map<String, Object> map = new HashMap<String, Object>();
        String message = "删除成功";
        try {
            for (Integer i:deptCodes){
                departmentService.delete(Department.class,i);
            }
            Boolean success = true;
            map.put("success", success);
            map.put("message", message);
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", e.getMessage());
        }
        return map;
    }

    @RequestMapping("/getTreeJson")
    @ResponseBody
    public void caiDan(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Department> li = departmentService.getList();
        String str = json(li);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(str);
    }

    private String json(List<?> li) {
        StringBuilder db = new StringBuilder();
        db.append("[");
        for (int i = 0; i < li.size(); i++) {
            Department dept = (Department) li.get(i);
            String strTemp = "";
            if (dept.getDepartments().size() > 0) {
                strTemp = " ,\"leaf\": \"false\" ,\"children\": " + json(Arrays.asList(dept.getDepartments().toArray()));
            } else {
                strTemp = " ,\"leaf\": \"true\" ";
            }
            if ((li.size() - 1) == i) {
                db.append("{\"text\": \"" + dept.getDeptName() + "\",\"id\":\"" + dept.getDeptCode() + "\"" + strTemp + "}");
            } else {
                db.append("{\"text\": \"" + dept.getDeptName() + "\",\"id\":\"" + dept.getDeptCode() + "\"" + strTemp + "},");
            }
        }
        db.append(" ]");
        return db.toString();
    }

}
